package com.bstek.weixin.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bstek.weixin.ase.WXBizMsgCrypt;
import com.bstek.weixin.utils.ConstantlUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;



/**
 * 微信 回调 servlet类
 * @author snail
 * @date 2019年1月2日
 */
public class WeixinServlet extends HttpServlet{

	private static final long serialVersionUID = 4440739483644821988L;



	/**
	 * url验证
	 * @author snail
	 * @date 2018年12月13日
	 * @param request
	 * @param response 
	 * @throws IOException 
	 */
	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response) {
		//获取 url参数
		String msgsignature =request.getParameter("msg_signature");//微信加密签名
		String timestamp =request.getParameter("timestamp");//时间戳
		String nonce =request.getParameter("nonce");//随机数 
		String echostr =request.getParameter("echostr");//随机 字符串
		//获取返回流
		PrintWriter printWriter=null;
		try {
			printWriter=response.getWriter();
			// 通过检验msg_signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			WXBizMsgCrypt wmc=new WXBizMsgCrypt(ConstantlUtil.token, ConstantlUtil.encodingAESKey,
					ConstantlUtil.corpId);
			String result=wmc.VerifyURL(msgsignature, timestamp, nonce, echostr);
			if(result==null) { //失败处理
				result=ConstantlUtil.token;
			}
			System.out.println("接口返回信息"+result);
			//return result;
			printWriter.write(result);
			printWriter.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(printWriter!=null) {
				printWriter.close();
			}
		}
	}


	/**
	 * 微信回调post 处理
	 * @author snail
	 * @date 2018年12月13日
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
		//获取 url参数
		String msgsignature =request.getParameter("msg_signature");//微信加密签名
		String timestamp =request.getParameter("timestamp");//时间戳
		String nonce =request.getParameter("nonce");//随机数 
		String line=null;//随机 字符串
		StringBuilder echostr=new StringBuilder();
		BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream()));
		while((line=br.readLine())!=null) {
			echostr.append(line);
		}
		br.close(); //关闭流
		System.out.println("接口返回:[微信加密签名]"+msgsignature+"[时间戳]"+timestamp+"[nonce]"+nonce);
		System.out.println("接口返回:"+echostr);
		if(StringUtils.hasText(echostr)) {
			//对返回的 xml做处理\
			String echostrStr=echostr.toString();
			String corpId=echostrStr.substring(echostrStr.indexOf("<ToUserName><![CDATA[")+21, echostrStr.indexOf("]]></ToUserName>"));
			if(ConstantlUtil.corpId.equals(corpId)) {
				//判断是否 微信端发 的请求
				echostrStr=echostrStr.substring(echostrStr.indexOf("<Encrypt><![CDATA[")+18,echostrStr.indexOf("]]></Encrypt>"));
			}
			//获取返回流
			PrintWriter printWriter=null;
			try {
				printWriter=response.getWriter();
				// 通过检验msg_signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
				WXBizMsgCrypt wmc=new WXBizMsgCrypt(ConstantlUtil.token, ConstantlUtil.encodingAESKey,
						ConstantlUtil.corpId);
				String result=wmc.VerifyURL(msgsignature, timestamp, nonce, echostrStr);
				if(result==null) { //失败处理
					result=ConstantlUtil.token;
				}
				System.out.println("接口返回信息"+result);
				printWriter.write(result);
				printWriter.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if(printWriter!=null) {
					printWriter.close();
				}
				if(br!=null) {
					br.close();
				}
			}
		}else {
			System.out.println("echostr内容返回为null");
		}
	}
	
	
	public static void main(String[] args) throws Exception {
		String test="tot4Hk2H9LZttqi6AHFF6wSsjQjEtpoDwYnUdQk0OwNUok8uvYIcwrJH5LrAYdRLjUy"
				+ "eOGV7816I8UhYNoU8OPrmeYniG344MA2Zsx3gvQJPdUF88KBKeN0OJMg4heFoGa2zwtlE+4e+Gjs0"
				+ "1MHyDw6Jw3IIqcNH4nqdnkw+nKwnXMua0eNpPIxIgvsqDF1hqoi7/Kg3ZCL5X9L1t4vnScymvH/SvOvI"
				+ "nE6Or0MPmWtDtdnuwckvDTzyehKix+T9ZRhzrTieln0B6w1Z8yFFuAwuU6tfyNtJDszNhboB4Xuxk+gvpEUl"
				+ "Rbg6n2OfZ8B/s3gFMu6wnkPgv40z90ntBhRbMHAP+SlVwAjT1lhjdO2M+Or6u0g4sADk9kgwS+4S3ODN3ziahx"
				+ "iHPvKXdLWYth8PINzMlpXx5JQBBQNfESABNB4sNcW4q57RrUxNjQss6BCokHKabC48zChnNitUPnXiFk3zwvM7f"
				+ "eU4QykucM/bsE5pfObHBPAXD5jg/34Wn7rYDe/a3W53CJvzYJ9+XsxQUHzQNvUUBzXSoLtvsh8LHgB/NnW4aX6j"
				+ "jPCIB5t3QuY403r8hb3UjzxSaZCSEbizfkNAiy5AGor8kessu7fIjvVLkgXZ+FTfZuzO/xCj";
		// 通过检验msg_signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		WXBizMsgCrypt wmc=new WXBizMsgCrypt(ConstantlUtil.token, ConstantlUtil.encodingAESKey,
				ConstantlUtil.corpId);
		String result=wmc.VerifyURL("42793f74d46177e8f109b6999f973b7293fa17f3", "1545229366", "1544609692", 
				test);
		System.out.println("解密之后的结果："+result);
		if(StringUtils.hasText(result)) {
			result="<?xml version='1.0' encoding='UTF-8'?>"+result;
			System.out.println(result);
			Document document=DocumentHelper.parseText(result);
			Element root=document.getRootElement();
			System.out.println(document);
			String username=root.elementText("UserID"); //xml信息
			System.out.println(username);
		}
	}
}
